package com.liuweiheng.cloudproviderpayment8002.mq.direct;

import com.liuweiheng.cloudproviderpayment8002.mq.MultiConstant;
import com.liuweiheng.cloudproviderpayment8002.util.RabbitMQUtil;
import com.rabbitmq.client.*;

import java.io.IOException;

public class Consumer {

    public static void main(String[] args) throws IOException {
        // 获取MQ连接
        Connection connection = RabbitMQUtil.getConnection();

        // 创建通道
        Channel channel = connection.createChannel();

        // 声明交换机
        channel.exchangeDeclare(Provider.EXCHANGE_NAME, MultiConstant.DIRECT_EXCHANGE_TYPE, true);

        // 创建临时队列
        String queueName = channel.queueDeclare().getQueue();

        // 绑定队列与交换机，并制定路由
        channel.queueBind(queueName, Provider.EXCHANGE_NAME, Provider.INFO);
        channel.queueBind(queueName, Provider.EXCHANGE_NAME, Provider.ERROR);
        channel.queueBind(queueName, Provider.EXCHANGE_NAME, Provider.WARNING);


        Channel finalChannel = channel;

        // 监听并消费消息
        channel.basicConsume(queueName, false, new DefaultConsumer(finalChannel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费者1：" + new String(body));
                finalChannel.basicAck(envelope.getDeliveryTag(), false);
            }
        });

    }

}
